package com.coocaa.aries.core.base.exception;

import com.coocaa.aries.core.base.builder.ExceptionBuilder;
import com.coocaa.aries.core.base.model.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.yaml.snakeyaml.constructor.DuplicateKeyException;

import java.util.HashMap;
import java.util.Map;

/**
 * @author : bijiahao
 * @date : 2019/4/6.
 * @description: 统一异常处理
 */
@RestControllerAdvice
public class AriesExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(AriesExceptionHandler.class);


    /**
     * 处理自定义异常
     */
    @ExceptionHandler(AriesException.class)
    public R handleRRException(AriesException e) {
        log.error(e.getMessage());
        R r = new R();
        r.put("success", false);
        r.put("code", "1001");
        r.put("msg", e.getMessage());
        return r;
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public R handleDuplicateKeyException(DuplicateKeyException e) {
        log.error(ExceptionUtil.getStackTraceAsString(e));
        return R.error("数据库中已存在该记录");
    }
    
    @ExceptionHandler(IllegalArgumentException.class)
    public R handleIllegalArgumentException(IllegalArgumentException e) {
        log.error(ExceptionUtil.getStackTraceAsString(e));
        return R.error(e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public R handleException(Exception e) {
        log.error(ExceptionUtil.getStackTraceAsString(e));
        Map<String, Object> stackTrace = new HashMap<>(1);
        stackTrace.put("stackTrace", ExceptionUtil.getStackTraceAsString(e));
        ExceptionBuilder.Builder builder = ExceptionBuilder.newBuilder()
                .withOpParams(stackTrace)
                .withDetailMsg(e.getMessage());
        return R.error(builder.build());
    }
}
